# routes/article_routes.py
from flask import Blueprint
from models.article import Article
import uuid
from flask import Flask, request, jsonify
from utils.logger import logger
import os

from utils.response import api_response

article_bp = Blueprint('/article', __name__)


from models.database import db
import json
# 正确的导入语句（根据实际文件名调整）
from crawler.JgCrawler import JgCrawler

@article_bp.route('/article/test')
def test():
    return  api_response(data={'orders': ['order1', 'order2', 'order3']})

# 分页获取文章列表
@article_bp.route('/article/list', methods=['GET'])
def get_article_list():
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('page_size', 10, type=int)
    type = request.args.get('type')
    category = request.args.get("category")
    filter = Article.query
    if type:
        filter = filter.filter_by(type=type)
    if category:
        filter = filter.filter_by(category=category)
    articles = filter.order_by(Article.add_time.desc()).paginate(page=page, per_page=page_size)
    return api_response(data={
        'articles': [article.to_dict() for article in articles.items],
        'total': articles.total,
        'page': page,
        'page_size': page_size
    })

# 分页获取文章详情
@article_bp.route('/article/detail', methods=['GET'])
def get_article_detail():
    id = request.args.get('id', '', type=str)
    if id == '':
        return api_response(code=1, message="参数错误")
    article = Article.query.filter_by(id=id).first()
    if article is None:
        return api_response(code=1, message="文章不存在")
    return api_response(data=article.to_dict())

# 新增文章
@article_bp.route('/article/add', methods=['POST'])
def add_article():
    data = request.json
    if 'title' not in data or 'content' not in data:
        return api_response(code=1, message="参数错误")
    article = Article(id=str(uuid.uuid4()), title=data['title'], content=data['content'])
    db.session.add(article)
    db.session.commit()
    return api_response(data=article.to_dict())

# 更新文章
@article_bp.route('/article/update', methods=['POST'])
def update_article():
    data = request.json
    if 'id' not in data or 'title' not in data or 'content' not in data:
        return api_response(code=1, message="参数错误")
    article:Article = Article.query.filter_by(id=data['id']).first()
    if article is None:
        return api_response(code=1, message="文章不存在")
    article.title = data['title']
    article.content = data['content']
    db.session.commit()
    return api_response(data=article.to_dict())

# 删除文章
@article_bp.route('/article/delete', methods=['POST'])
def delete_article():
    data = request.json
    if 'id' not in data:
        return api_response(code=1, message="参数错误")
    article = Article.query.filter_by(id=data['id']).first()
    if article is None:
        return api_response(code=1, message="文章不存在")
    db.session.delete(article)
    db.session.commit()
    return api_response(message="删除成功")




